package io;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketBIOTest {
    public static void main(String[] args) {
        CountDownServer server = new CountDownServer();
        server.start();
        new Client().start();
//        new Client().start();
    }

    static class CountDownServer extends Thread {
        private ServerSocket serverSocket;
        public static final int port = 8989;

        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(port);
                ExecutorService executor = Executors.newFixedThreadPool(8);
                while (true) {
                    Socket socket = serverSocket.accept();
                    executor.execute(new RequestHandler(socket));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class RequestHandler extends Thread {

        private Socket socket;

        public RequestHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                System.out.println("handle" + socket.toString());
                PrintWriter out = new PrintWriter(socket.getOutputStream());
                out.println("-- hello!");
                out.println("-- start countdown");
                out.flush();
                for (int i = 0; i < 10; i++) {
                    out.println(10 - i);
                    out.flush();
                    sleep(1000);
                }
                out.println("-- end bye!");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (!socket.isClosed()) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class Client extends Thread {

        @Override
        public void run() {
            try (Socket client = new Socket(InetAddress.getLocalHost(), CountDownServer.port)) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                String str;
                while ((str = bufferedReader.readLine()) != null) {
                    System.out.println(str);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
